using DocumentCreationSystem.Models;
using DocumentCreationSystem.Services;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using System.IO;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 自主规划服务 - Agent根据用户需求自主规划人物及工作流并实施
    /// </summary>
    public class AutonomousPlanningService
    {
        private readonly ILogger<AutonomousPlanningService> _logger;
        private readonly IAIService _aiService;
        private readonly EnhancedIntentRecognizer _intentRecognizer;
        private readonly CharacterPlanningEngine _characterPlanner;
        private readonly WorkflowOrchestrationEngine _workflowEngine;
        private readonly ExecutionMonitoringService _executionMonitor;
        private readonly IProjectService _projectService;
        private readonly IDataStorageService _dataStorage;

        public AutonomousPlanningService(
            ILogger<AutonomousPlanningService> logger,
            IAIService aiService,
            EnhancedIntentRecognizer intentRecognizer,
            CharacterPlanningEngine characterPlanner,
            WorkflowOrchestrationEngine workflowEngine,
            ExecutionMonitoringService executionMonitor,
            IProjectService projectService,
            IDataStorageService dataStorage)
        {
            _logger = logger;
            _aiService = aiService;
            _intentRecognizer = intentRecognizer;
            _characterPlanner = characterPlanner;
            _workflowEngine = workflowEngine;
            _executionMonitor = executionMonitor;
            _projectService = projectService;
            _dataStorage = dataStorage;
        }

        /// <summary>
        /// 根据用户需求自主规划并实施
        /// </summary>
        public async Task<AutonomousPlanResult> PlanAndExecuteAsync(string userRequest, string? projectId = null, IProgress<(int progress, string message)>? progressCallback = null, string? preferredSaveRootPath = null)
        {
            try
            {
                _logger.LogInformation($"开始自主规划处理用户请求: {userRequest}");

                // 1. 意图理解和需求分析
                progressCallback?.Report((10, "正在分析用户需求..."));
                var intent = await AnalyzeUserIntentAsync(userRequest, projectId);

                // 2. 生成综合规划方案
                progressCallback?.Report((30, "正在生成规划方案..."));
                var planningResult = await GenerateComprehensivePlanAsync(intent);

                // 3. 执行规划方案
                progressCallback?.Report((60, "正在执行规划方案..."));
                var executionResult = await ExecutePlanAsync(planningResult);

                // 4. 监控和优化
                progressCallback?.Report((90, "正在优化和生成报告..."));
                var finalResult = await MonitorAndOptimizeAsync(executionResult);

                // 5. 保存规划文件
                progressCallback?.Report((95, "正在保存规划文件..."));
                await SavePlanningFilesAsync(finalResult, projectId, preferredSaveRootPath);

                progressCallback?.Report((100, "规划完成"));
                _logger.LogInformation("自主规划处理完成");
                return finalResult;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "自主规划处理失败");
                throw;
            }
        }

        /// <summary>
        /// 分析用户意图
        /// </summary>
        private async Task<EnhancedUserIntent> AnalyzeUserIntentAsync(string userRequest, string? projectId)
        {
            // 获取项目上下文
            var projectContext = await GetProjectContextAsync(projectId);
            
            // 使用增强的意图识别器
            var complexIntent = await _intentRecognizer.AnalyzeUserIntentAsync(userRequest);
            
            // 构建增强的用户意图
            var enhancedIntent = new EnhancedUserIntent
            {
                OriginalRequest = userRequest,
                ComplexIntent = complexIntent,
                ProjectContext = projectContext,
                RequiresCharacterPlanning = DetermineCharacterPlanningNeed(complexIntent),
                RequiresWorkflowPlanning = DetermineWorkflowPlanningNeed(complexIntent),
                PlanningScope = DeterminePlanningScope(complexIntent),
                AnalyzedAt = DateTime.Now
            };

            return enhancedIntent;
        }

        /// <summary>
        /// 生成综合规划方案
        /// </summary>
        private async Task<ComprehensivePlan> GenerateComprehensivePlanAsync(EnhancedUserIntent intent)
        {
            var plan = new ComprehensivePlan
            {
                UserIntent = intent,
                CreatedAt = DateTime.Now
            };

            // 若用户请求较为笼统且未触发任何专项规划，启用合理的默认规划项
            if (!intent.RequiresCharacterPlanning && !intent.RequiresWorkflowPlanning)
            {
                _logger.LogInformation("未检测到明确的角色/工作流关键词，启用默认的角色与工作流规划");
                intent.RequiresCharacterPlanning = true;
                intent.RequiresWorkflowPlanning = true;
            }

            // 并行生成不同类型的规划
            var tasks = new List<Task>();

            if (intent.RequiresCharacterPlanning)
            {
                tasks.Add(Task.Run(async () =>
                {
                    plan.CharacterPlan = await _characterPlanner.GenerateCharacterPlanAsync(intent);
                }));
            }

            if (intent.RequiresWorkflowPlanning)
            {
                tasks.Add(Task.Run(async () =>
                {
                    plan.WorkflowPlan = await _workflowEngine.GenerateWorkflowPlanAsync(intent);
                }));
            }

            // 等待所有规划任务完成
            await Task.WhenAll(tasks);

            // 整合和优化规划
            plan = await IntegrateAndOptimizePlanAsync(plan);

            return plan;
        }

        /// <summary>
        /// 执行规划方案
        /// </summary>
        private async Task<PlanExecutionResult> ExecutePlanAsync(ComprehensivePlan plan)
        {
            var executionResult = new PlanExecutionResult
            {
                Plan = plan,
                StartedAt = DateTime.Now,
                Status = ExecutionStatus.Running
            };

            try
            {
                // 创建执行上下文
                var executionContext = new Models.ExecutionContext
                {
                    Plan = plan,
                    ProjectId = plan.UserIntent.ProjectContext?.ProjectId,
                    ExecutionId = Guid.NewGuid().ToString()
                };

                // 按优先级和依赖关系执行任务
                if (plan.CharacterPlan != null)
                {
                    var characterResult = await ExecuteCharacterPlanAsync(plan.CharacterPlan, executionContext);
                    executionResult.CharacterExecutionResult = characterResult;
                }

                if (plan.WorkflowPlan != null)
                {
                    var workflowResult = await ExecuteWorkflowPlanAsync(plan.WorkflowPlan, executionContext);
                    executionResult.WorkflowExecutionResult = workflowResult;
                }

                executionResult.Status = ExecutionStatus.Completed;
                executionResult.CompletedAt = DateTime.Now;
            }
            catch (Exception ex)
            {
                executionResult.Status = ExecutionStatus.Failed;
                executionResult.ErrorMessage = ex.Message;
                executionResult.CompletedAt = DateTime.Now;
                _logger.LogError(ex, "规划执行失败");
            }

            return executionResult;
        }

        /// <summary>
        /// 监控和优化执行结果
        /// </summary>
        private async Task<AutonomousPlanResult> MonitorAndOptimizeAsync(PlanExecutionResult executionResult)
        {
            // 使用执行监控服务分析结果
            var monitoringResult = await _executionMonitor.AnalyzeExecutionResultAsync(executionResult);
            
            // 生成优化建议
            var optimizationSuggestions = await GenerateOptimizationSuggestionsAsync(executionResult, monitoringResult);
            
            // 构建最终结果
            var finalResult = new AutonomousPlanResult
            {
                ExecutionResult = executionResult,
                MonitoringResult = monitoringResult,
                OptimizationSuggestions = optimizationSuggestions,
                Success = executionResult.Status == ExecutionStatus.Completed,
                CompletedAt = DateTime.Now
            };

            // 如果有优化建议且用户允许，自动应用优化
            if (optimizationSuggestions.Any() && ShouldAutoApplyOptimizations(optimizationSuggestions))
            {
                finalResult = await ApplyOptimizationsAsync(finalResult);
            }

            return finalResult;
        }

        /// <summary>
        /// 执行角色规划
        /// </summary>
        private async Task<CharacterExecutionResult> ExecuteCharacterPlanAsync(CharacterPlan characterPlan, Models.ExecutionContext context)
        {
            return await _characterPlanner.ExecutePlanAsync(characterPlan, context);
        }

        /// <summary>
        /// 执行工作流规划
        /// </summary>
        private async Task<WorkflowExecutionResult> ExecuteWorkflowPlanAsync(WorkflowPlan workflowPlan, Models.ExecutionContext context)
        {
            return await _workflowEngine.ExecutePlanAsync(workflowPlan, context);
        }

        /// <summary>
        /// 获取项目上下文
        /// </summary>
        private async Task<ProjectContext?> GetProjectContextAsync(string? projectId)
        {
            if (string.IsNullOrEmpty(projectId))
                return null;

            try
            {
                var project = await _projectService.GetProjectAsync(int.Parse(projectId));
                if (project == null)
                    return null;

                return new ProjectContext
                {
                    ProjectId = projectId,
                    ProjectName = project.Name,
                    ProjectType = project.Type,
                    ProjectPath = project.RootPath,
                    // 可以添加更多上下文信息
                };
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, $"获取项目上下文失败: {projectId}");
                return null;
            }
        }

        /// <summary>
        /// 判断是否需要角色规划
        /// </summary>
        private bool DetermineCharacterPlanningNeed(ComplexIntent intent)
        {
            // 更健壮的关键词判定（覆盖更多用户常用表达），并对泛化“规划/小说/故事”等触发角色规划
            var strongKeywords = new[] { "角色", "人物", "主角", "配角", "反派", "人设", "人物设定", "人物关系", "角色发展", "人物塑造", "登场人物", "character", "cast" };
            if (strongKeywords.Any(k => intent.UserInput.Contains(k, StringComparison.OrdinalIgnoreCase))) return true;

            var genericTriggers = new[] { "规划", "小说", "故事", "世界观", "世界设定", "背景" };
            if (genericTriggers.Any(k => intent.UserInput.Contains(k, StringComparison.OrdinalIgnoreCase))) return true;

            return false;
        }

        /// <summary>
        /// 判断是否需要工作流规划
        /// </summary>
        private bool DetermineWorkflowPlanningNeed(ComplexIntent intent)
        {
            // 更健壮的关键词判定，并对泛化“规划/生成/创作”等触发工作流规划
            var strongKeywords = new[] { "流程", "步骤", "计划", "安排", "执行", "工作流", "任务", "路线图", "roadmap", "流程图", "写作流程", "写作计划", "生成步骤", "pipeline" };
            if (strongKeywords.Any(k => intent.UserInput.Contains(k, StringComparison.OrdinalIgnoreCase))) return true;

            var genericTriggers = new[] { "规划", "生成", "创作", "制定", "安排" };
            if (genericTriggers.Any(k => intent.UserInput.Contains(k, StringComparison.OrdinalIgnoreCase))) return true;

            return false;
        }

        /// <summary>
        /// 确定规划范围
        /// </summary>
        private PlanningScope DeterminePlanningScope(ComplexIntent intent)
        {
            // 根据意图复杂度和类型确定规划范围
            if (intent.IntentType == IntentType.ProjectManagement)
                return PlanningScope.Project;
            else if (intent.IntentType == IntentType.ContentGeneration)
                return PlanningScope.Content;
            else
                return PlanningScope.Task;
        }

        /// <summary>
        /// 整合和优化规划
        /// </summary>
        private async Task<ComprehensivePlan> IntegrateAndOptimizePlanAsync(ComprehensivePlan plan)
        {
            // 使用AI服务优化规划的整合性和一致性
            var optimizationPrompt = BuildPlanOptimizationPrompt(plan);
            var optimizationResult = await _aiService.GenerateTextAsync(optimizationPrompt, 2000, 0.7f);
            
            // 解析优化建议并应用
            plan.OptimizationNotes = optimizationResult;
            plan.IsOptimized = true;
            
            return plan;
        }

        /// <summary>
        /// 构建规划优化提示
        /// </summary>
        private string BuildPlanOptimizationPrompt(ComprehensivePlan plan)
        {
            return $@"请分析以下综合规划方案，提供优化建议：

用户需求：{plan.UserIntent.OriginalRequest}

角色规划：{(plan.CharacterPlan != null ? "已包含" : "未包含")}
工作流规划：{(plan.WorkflowPlan != null ? "已包含" : "未包含")}

请提供：
1. 规划的完整性分析
2. 各部分之间的协调性建议
3. 执行顺序优化建议
4. 潜在风险和应对措施

优化建议：";
        }

        /// <summary>
        /// 生成优化建议
        /// </summary>
        private async Task<List<OptimizationSuggestion>> GenerateOptimizationSuggestionsAsync(
            PlanExecutionResult executionResult, 
            MonitoringResult monitoringResult)
        {
            var suggestions = new List<OptimizationSuggestion>();
            
            // 基于执行结果和监控数据生成优化建议
            if (monitoringResult.PerformanceMetrics.ExecutionTime > TimeSpan.FromMinutes(10))
            {
                suggestions.Add(new OptimizationSuggestion
                {
                    Type = OptimizationType.Performance,
                    Description = "执行时间较长，建议优化任务并行度",
                    Priority = OptimizationPriority.Medium,
                    AutoApplicable = true
                });
            }

            return suggestions;
        }

        /// <summary>
        /// 判断是否应该自动应用优化
        /// </summary>
        private bool ShouldAutoApplyOptimizations(List<OptimizationSuggestion> suggestions)
        {
            return suggestions.All(s => s.AutoApplicable && s.Priority != OptimizationPriority.High);
        }

        /// <summary>
        /// 应用优化建议
        /// </summary>
        private async Task<AutonomousPlanResult> ApplyOptimizationsAsync(AutonomousPlanResult result)
        {
            // 实现优化应用逻辑
            result.OptimizationsApplied = true;
            return result;
        }

        /// <summary>
        /// 保存规划文件到项目目录
        /// </summary>
        private async Task SavePlanningFilesAsync(AutonomousPlanResult result, string? projectId, string? preferredSaveRootPath = null)
        {
            try
            {
                // 确定保存路径
                string savePath;
                if (!string.IsNullOrEmpty(projectId))
                {
                    // 如果有项目ID，优先使用传入的首选保存根路径，否则根据项目ID获取路径
                    savePath = !string.IsNullOrWhiteSpace(preferredSaveRootPath) ? preferredSaveRootPath : (await GetProjectPathAsync(projectId) ?? GetDefaultPlanningPath());
                }
                else
                {
                    savePath = !string.IsNullOrWhiteSpace(preferredSaveRootPath) ? preferredSaveRootPath : GetDefaultPlanningPath();
                }

                var planningDir = Path.Combine(savePath, "自主规划");
                Directory.CreateDirectory(planningDir);

                var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");

                // 设置规划文件保存路径
                result.PlanningFilesPath = planningDir;
                result.SavedFiles.Clear();

                // 1. 保存规划概览
                var overviewPath = Path.Combine(planningDir, $"规划概览_{timestamp}.txt");
                var overviewContent = GeneratePlanningOverviewContent(result);
                await File.WriteAllTextAsync(overviewPath, overviewContent, System.Text.Encoding.UTF8);

                // 添加文件信息
                var overviewFileInfo = new FileInfo(overviewPath);
                result.SavedFiles.Add(new PlanningFileInfo
                {
                    FileName = Path.GetFileName(overviewPath),
                    FilePath = overviewPath,
                    FileType = "规划概览",
                    FileSize = overviewFileInfo.Length,
                    CreatedAt = DateTime.Now
                });

                // 2. 保存角色规划（如果有）
                if (result.ExecutionResult.CharacterExecutionResult != null)
                {
                    var characterPath = Path.Combine(planningDir, $"角色规划_{timestamp}.txt");
                    var characterContent = GenerateCharacterPlanContent(result.ExecutionResult.CharacterExecutionResult);
                    await File.WriteAllTextAsync(characterPath, characterContent, System.Text.Encoding.UTF8);

                    var characterFileInfo = new FileInfo(characterPath);
                    result.SavedFiles.Add(new PlanningFileInfo
                    {
                        FileName = Path.GetFileName(characterPath),
                        FilePath = characterPath,
                        FileType = "角色规划",
                        FileSize = characterFileInfo.Length,
                        CreatedAt = DateTime.Now
                    });
                }

                // 3. 保存工作流规划（如果有）
                if (result.ExecutionResult.WorkflowExecutionResult != null)
                {
                    var workflowPath = Path.Combine(planningDir, $"工作流规划_{timestamp}.txt");
                    var workflowContent = GenerateWorkflowPlanContent(result.ExecutionResult.WorkflowExecutionResult);
                    await File.WriteAllTextAsync(workflowPath, workflowContent, System.Text.Encoding.UTF8);

                    var workflowFileInfo = new FileInfo(workflowPath);
                    result.SavedFiles.Add(new PlanningFileInfo
                    {
                        FileName = Path.GetFileName(workflowPath),
                        FilePath = workflowPath,
                        FileType = "工作流规划",
                        FileSize = workflowFileInfo.Length,
                        CreatedAt = DateTime.Now
                    });
                }

                // 4. 保存优化建议
                if (result.OptimizationSuggestions.Any())
                {
                    var optimizationPath = Path.Combine(planningDir, $"优化建议_{timestamp}.txt");
                    var optimizationContent = GenerateOptimizationContent(result.OptimizationSuggestions);
                    await File.WriteAllTextAsync(optimizationPath, optimizationContent, System.Text.Encoding.UTF8);

                    var optimizationFileInfo = new FileInfo(optimizationPath);
                    result.SavedFiles.Add(new PlanningFileInfo
                    {
                        FileName = Path.GetFileName(optimizationPath),
                        FilePath = optimizationPath,
                        FileType = "优化建议",
                        FileSize = optimizationFileInfo.Length,
                        CreatedAt = DateTime.Now
                    });
                }

                _logger.LogInformation($"规划文件已保存到: {planningDir}，共保存 {result.SavedFiles.Count} 个文件");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存规划文件失败");
            }
        }

        /// <summary>
        /// 获取项目路径
        /// </summary>
        private async Task<string?> GetProjectPathAsync(string projectId)
        {
            try
            {
                // 尝试通过数据存储服务获取项目信息
                var projects = await _dataStorage.GetProjectsAsync();
                if (int.TryParse(projectId, out int id))
                {
                    var project = projects.FirstOrDefault(p => p.Id == id);
                    return project?.RootPath;
                }
                return null;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, $"获取项目路径失败，项目ID: {projectId}");
                return null;
            }
        }

        /// <summary>
        /// 获取默认规划保存路径
        /// </summary>
        private string GetDefaultPlanningPath()
        {
            var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            return Path.Combine(documentsPath, "AI创作系统", "自主规划");
        }

        /// <summary>
        /// 生成规划概览内容
        /// </summary>
        private string GeneratePlanningOverviewContent(AutonomousPlanResult result)
        {
            var content = new System.Text.StringBuilder();
            content.AppendLine("# 自主规划概览报告");
            content.AppendLine($"生成时间: {result.CompletedAt:yyyy-MM-dd HH:mm:ss}");
            content.AppendLine($"执行状态: {(result.Success ? "成功" : "失败")}");
            content.AppendLine();

            if (result.ExecutionResult.StartedAt != default && result.ExecutionResult.CompletedAt.HasValue)
            {
                var duration = result.ExecutionResult.CompletedAt.Value - result.ExecutionResult.StartedAt;
                content.AppendLine($"执行时间: {duration:hh\\:mm\\:ss}");
            }

            content.AppendLine();
            content.AppendLine("## 执行摘要");
            if (!string.IsNullOrEmpty(result.Summary))
            {
                content.AppendLine(result.Summary);
            }
            else
            {
                content.AppendLine("本次智能规划已成功完成，系统根据用户需求自动生成了相应的角色和工作流规划。");
                content.AppendLine("所有规划内容都经过AI智能分析和优化，确保符合项目需求和最佳实践。");
            }

            // 添加规划内容概述
            content.AppendLine();
            content.AppendLine("## 规划内容概述");

            if (result.ExecutionResult.CharacterExecutionResult != null && result.ExecutionResult.CharacterExecutionResult.CreatedCharacters.Any())
            {
                content.AppendLine($"✅ **角色规划**: 成功创建 {result.ExecutionResult.CharacterExecutionResult.CreatedCharacters.Count} 个角色");
                foreach (var character in result.ExecutionResult.CharacterExecutionResult.CreatedCharacters.Take(3))
                {
                    content.AppendLine($"   - {character.Name}: {character.Description?.Substring(0, Math.Min(character.Description.Length, 50))}...");
                }
                if (result.ExecutionResult.CharacterExecutionResult.CreatedCharacters.Count > 3)
                {
                    content.AppendLine($"   - 以及其他 {result.ExecutionResult.CharacterExecutionResult.CreatedCharacters.Count - 3} 个角色...");
                }
            }

            if (result.ExecutionResult.WorkflowExecutionResult != null && result.ExecutionResult.WorkflowExecutionResult.StepResults.Any())
            {
                content.AppendLine($"✅ **工作流规划**: 执行了 {result.ExecutionResult.WorkflowExecutionResult.StepResults.Count} 个规划步骤");
                var completedSteps = result.ExecutionResult.WorkflowExecutionResult.StepResults.Count(s => s.Status == ExecutionStatus.Completed);
                content.AppendLine($"   - 成功完成: {completedSteps} 个步骤");
                content.AppendLine($"   - 执行效率: {(completedSteps * 100.0 / result.ExecutionResult.WorkflowExecutionResult.StepResults.Count):F1}%");
            }

            if (result.OptimizationSuggestions.Any())
            {
                content.AppendLine($"💡 **优化建议**: 生成了 {result.OptimizationSuggestions.Count} 条优化建议");
            }

            // 性能指标
            if (result.MonitoringResult.PerformanceMetrics != null)
            {
                content.AppendLine();
                content.AppendLine("## 性能指标");
                content.AppendLine($"- 完成任务数: {result.MonitoringResult.PerformanceMetrics.TasksCompleted}");
                content.AppendLine($"- 失败任务数: {result.MonitoringResult.PerformanceMetrics.TasksFailed}");
                content.AppendLine($"- 成功率: {result.MonitoringResult.PerformanceMetrics.SuccessRate:P2}");
            }

            // 添加使用建议
            content.AppendLine();
            content.AppendLine("## 使用建议");
            content.AppendLine("1. 请查看详细的角色规划文件，了解每个角色的完整设定");
            content.AppendLine("2. 工作流规划文件包含了具体的执行步骤和操作指南");
            content.AppendLine("3. 优化建议可以帮助您进一步完善规划内容");
            content.AppendLine("4. 所有规划内容都可以根据实际需要进行调整和修改");

            return content.ToString();
        }

        /// <summary>
        /// 生成角色规划内容
        /// </summary>
        private string GenerateCharacterPlanContent(CharacterExecutionResult characterResult)
        {
            var content = new System.Text.StringBuilder();
            content.AppendLine("# 角色规划报告");
            content.AppendLine($"生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            content.AppendLine();

            content.AppendLine("## 规划概述");
            content.AppendLine($"本次角色规划共创建了 {characterResult.CreatedCharacters.Count} 个角色，");
            content.AppendLine("每个角色都经过AI智能分析和设计，具有完整的背景设定、属性配置和发展轨迹。");
            content.AppendLine();

            content.AppendLine("## 创建的角色详情");

            foreach (var character in characterResult.CreatedCharacters)
            {
                content.AppendLine($"### {character.Name}");
                content.AppendLine();

                // 基础信息
                content.AppendLine("**基础信息**");
                content.AppendLine($"- 角色名称: {character.Name}");
                content.AppendLine($"- 角色描述: {character.Description}");
                content.AppendLine();

                // 属性信息
                if (!string.IsNullOrEmpty(character.Attributes))
                {
                    content.AppendLine("**属性设定**");
                    try
                    {
                        var attributes = JsonSerializer.Deserialize<Dictionary<string, object>>(character.Attributes);
                        foreach (var attr in attributes)
                        {
                            content.AppendLine($"- {attr.Key}: {attr.Value}");
                        }
                    }
                    catch
                    {
                        content.AppendLine($"- 属性数据: {character.Attributes}");
                    }
                    content.AppendLine();
                }

                // 技能信息
                if (!string.IsNullOrEmpty(character.Skills))
                {
                    content.AppendLine("**技能列表**");
                    try
                    {
                        var skills = JsonSerializer.Deserialize<Dictionary<string, object>>(character.Skills);
                        foreach (var skill in skills)
                        {
                            content.AppendLine($"- {skill.Key}: {skill.Value}");
                        }
                    }
                    catch
                    {
                        content.AppendLine($"- 技能数据: {character.Skills}");
                    }
                    content.AppendLine();
                }

                // 装备信息
                if (!string.IsNullOrEmpty(character.Equipment))
                {
                    content.AppendLine("**装备道具**");
                    try
                    {
                        var equipment = JsonSerializer.Deserialize<Dictionary<string, object>>(character.Equipment);
                        foreach (var item in equipment)
                        {
                            content.AppendLine($"- {item.Key}: {item.Value}");
                        }
                    }
                    catch
                    {
                        content.AppendLine($"- 装备数据: {character.Equipment}");
                    }
                    content.AppendLine();
                }

                content.AppendLine("---");
                content.AppendLine();
            }

            // 更新的角色
            if (characterResult.UpdatedCharacters.Any())
            {
                content.AppendLine("## 更新的角色");
                foreach (var characterId in characterResult.UpdatedCharacters)
                {
                    content.AppendLine($"- 角色ID: {characterId}");
                }
                content.AppendLine();
            }

            // 执行统计
            content.AppendLine("## 执行统计");
            content.AppendLine($"- 新创建角色数量: {characterResult.CreatedCharacters.Count}");
            content.AppendLine($"- 更新角色数量: {characterResult.UpdatedCharacters.Count}");

            if (characterResult.Metrics.Any())
            {
                content.AppendLine("- 其他指标:");
                foreach (var metric in characterResult.Metrics)
                {
                    content.AppendLine($"  - {metric.Key}: {metric.Value}");
                }
            }

            content.AppendLine();
            content.AppendLine("## 使用说明");
            content.AppendLine("1. 每个角色的详细设定可以根据实际需要进行调整");
            content.AppendLine("2. 角色之间的关系和互动可以在后续章节中进一步发展");
            content.AppendLine("3. 角色的成长轨迹应该与整体故事情节保持一致");
            content.AppendLine("4. 建议定期回顾和更新角色设定，确保角色发展的连贯性");

            return content.ToString();
        }

        /// <summary>
        /// 生成工作流规划内容
        /// </summary>
        private string GenerateWorkflowPlanContent(WorkflowExecutionResult workflowResult)
        {
            var content = new System.Text.StringBuilder();
            content.AppendLine("# 工作流规划报告");
            content.AppendLine($"生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            content.AppendLine();

            content.AppendLine("## 规划概述");
            content.AppendLine($"本次工作流规划共包含 {workflowResult.StepResults.Count} 个执行步骤，");
            content.AppendLine("每个步骤都经过AI智能分析和优化，确保执行效率和质量。");

            var completedSteps = workflowResult.StepResults.Count(s => s.Status == ExecutionStatus.Completed);
            var failedSteps = workflowResult.StepResults.Count(s => s.Status == ExecutionStatus.Failed);

            content.AppendLine($"执行成功率: {(completedSteps * 100.0 / workflowResult.StepResults.Count):F1}%");
            content.AppendLine();

            content.AppendLine("## 执行步骤详情");

            for (int i = 0; i < workflowResult.StepResults.Count; i++)
            {
                var stepResult = workflowResult.StepResults[i];

                content.AppendLine($"### 步骤 {i + 1}: {stepResult.StepId}");
                content.AppendLine();

                // 基础信息
                content.AppendLine("**基础信息**");
                content.AppendLine($"- 步骤ID: {stepResult.StepId}");
                content.AppendLine($"- 执行状态: {GetStatusDisplayName(stepResult.Status)}");

                if (stepResult.StartedAt != default && stepResult.CompletedAt.HasValue)
                {
                    var duration = stepResult.CompletedAt.Value - stepResult.StartedAt;
                    content.AppendLine($"- 执行耗时: {duration:hh\\:mm\\:ss}");
                    content.AppendLine($"- 开始时间: {stepResult.StartedAt:yyyy-MM-dd HH:mm:ss}");
                    content.AppendLine($"- 完成时间: {stepResult.CompletedAt:yyyy-MM-dd HH:mm:ss}");
                }

                content.AppendLine();

                // 执行输出
                if (!string.IsNullOrEmpty(stepResult.Output))
                {
                    content.AppendLine("**执行输出**");
                    content.AppendLine(stepResult.Output);
                    content.AppendLine();
                }

                // 错误信息
                if (!string.IsNullOrEmpty(stepResult.ErrorMessage))
                {
                    content.AppendLine("**错误信息**");
                    content.AppendLine(stepResult.ErrorMessage);
                    content.AppendLine();
                }

                content.AppendLine("---");
                content.AppendLine();
            }

            // 执行统计
            content.AppendLine("## 执行统计");
            content.AppendLine($"- 总步骤数: {workflowResult.StepResults.Count}");
            content.AppendLine($"- 成功步骤: {completedSteps}");
            content.AppendLine($"- 失败步骤: {failedSteps}");
            content.AppendLine($"- 成功率: {(completedSteps * 100.0 / workflowResult.StepResults.Count):F1}%");

            if (workflowResult.Outputs.Any())
            {
                content.AppendLine();
                content.AppendLine("## 输出数据");
                foreach (var output in workflowResult.Outputs)
                {
                    content.AppendLine($"- {output.Key}: {output.Value}");
                }
            }

            if (workflowResult.Metrics.Any())
            {
                content.AppendLine();
                content.AppendLine("## 性能指标");
                foreach (var metric in workflowResult.Metrics)
                {
                    content.AppendLine($"- {metric.Key}: {metric.Value}");
                }
            }

            content.AppendLine();
            content.AppendLine("## 使用建议");
            content.AppendLine("1. 成功执行的步骤可以作为后续工作的参考模板");
            content.AppendLine("2. 失败的步骤需要分析原因并进行相应的调整");
            content.AppendLine("3. 可以根据实际需要调整步骤的执行顺序和参数");
            content.AppendLine("4. 建议定期回顾工作流执行效果，持续优化流程");

            return content.ToString();
        }

        /// <summary>
        /// 获取状态显示名称
        /// </summary>
        private string GetStatusDisplayName(ExecutionStatus status)
        {
            return status switch
            {
                ExecutionStatus.Pending => "等待执行",
                ExecutionStatus.Running => "正在执行",
                ExecutionStatus.Completed => "执行成功",
                ExecutionStatus.Failed => "执行失败",
                ExecutionStatus.Cancelled => "已取消",
                _ => status.ToString()
            };
        }

        /// <summary>
        /// 生成优化建议内容
        /// </summary>
        private string GenerateOptimizationContent(List<OptimizationSuggestion> suggestions)
        {
            var content = new System.Text.StringBuilder();
            content.AppendLine("# 优化建议报告");
            content.AppendLine($"生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            content.AppendLine();

            foreach (var suggestion in suggestions.OrderBy(s => s.Priority))
            {
                content.AppendLine($"## {suggestion.Type} - {suggestion.Priority}");
                content.AppendLine(suggestion.Description);
                content.AppendLine($"可自动应用: {(suggestion.AutoApplicable ? "是" : "否")}");
                content.AppendLine();
            }

            return content.ToString();
        }
    }
}
